package com.github.shiqiyue.learn.curator;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/***
 *
 * @author wenyao.wu
 * @date 2019/1/21
 */
public class ClientUtil {

    public static final String DEFAULT_ZK_ADDRESS = "127.0.0.1:2181";

    public static final RetryPolicy RETRY__POLICY = new ExponentialBackoffRetry(1000, 3);

    public static CuratorFramework getClient(String address) {
        CuratorFramework client = CuratorFrameworkFactory.newClient(
                StringUtils.defaultString(address, DEFAULT_ZK_ADDRESS),
                RETRY__POLICY
        );
        client.start();
        return client;
    }

    public static void setData(CuratorFramework client, String path, byte[] data) throws Exception {
        client.setData().forPath(path, data);
    }

    public static byte[] getData(CuratorFramework client, String path) throws Exception {
        return client.getData().forPath(path);
    }

    public static void deleteNode(CuratorFramework client, String path, Boolean deletingChildrenIfNeeded) throws Exception {
        if (deletingChildrenIfNeeded) {
            client.delete().deletingChildrenIfNeeded().forPath(path);
        } else {
            client.delete().forPath(path);
        }

    }


}
